package com.emagic.manage.modules.loginmodule.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.emagic.manage.R;
import com.emagic.manage.common.ui.base.ToolBarActivity;
import com.emagic.manage.modules.loginmodule.presenter.LoginPresenter;
import com.emagic.manage.modules.loginmodule.view.LoginView;
import com.emagic.manage.utils.SpecialCharactersInputFilter;
import com.jakewharton.rxbinding.view.RxView;

import org.blankapp.validation.Rule;
import org.blankapp.validation.SimpleValidationListener;
import org.blankapp.validation.Validator;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.ButterKnife;

/**
 * 登录界面
 *
 * @author baoy
 * @version 1.0
 */
public class LoginActivity extends ToolBarActivity implements LoginView {

    public static final String EXTRA_FAILURE_PHONE = "autoLogin.failure.phone";

    @Inject
    LoginPresenter mPresenter;

    private ProgressDialog mProgressDialog;
    private String mNickName;
    private EditText mAccountEditor;
    private EditText mPasswordEditor;
    private Button mLoginSubmitButton;
    ;

    public static Intent getCallingIntent(Context context, String phone) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra(EXTRA_FAILURE_PHONE, phone);
        return intent;
    }

    private void setupUI() {
        getToolbar().setVisibility(View.GONE);

        //如果自动登录电话号码不为空,显示
        if (!TextUtils.isEmpty(mNickName)) {
            mAccountEditor.setText(mNickName);
            mAccountEditor.setSelection(mNickName.length());//将光标移至文字末尾
        }

        mPasswordEditor.setFilters(new InputFilter[]{new SpecialCharactersInputFilter("^[a-zA-Z0-9]+"), new InputFilter.LengthFilter(20)});
        mAccountEditor.setFilters(new InputFilter[]{new SpecialCharactersInputFilter("^[a-zA-Z0-9]+"), new InputFilter.LengthFilter(20)});

        //不显示返回按键
        if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }

    private void bindListener() {
        // 登录表单校验器
        Validator validator = new Validator();
        validator.add(Rule.with(mAccountEditor, "账号")
                .required()
                .regex("^[0-9a-zA-Z]{1,20}$"));
        validator.add(Rule.with(mPasswordEditor, "密码")
                .required()
                .minLength(6)
                .maxLength(20)
                .regex("^[0-9a-zA-Z]{6,20}$"));
        validator.setValidatorListener(new SimpleValidationListener() {
            @Override
            public void onSucceeded() {
                String phone = mAccountEditor.getText().toString();
                String password = mPasswordEditor.getText().toString();
                mPresenter.login(phone, password);
            }
        });

        //绑定登录按钮事件
        RxView.clicks(mLoginSubmitButton)
                .throttleFirst(1000, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    validator.validate();
                });

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNickName = getIntent().getStringExtra(EXTRA_FAILURE_PHONE);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        mPresenter.attachView(this);
        findvView();
        setupUI();
        bindListener();

    }

    private void findvView() {
        mAccountEditor = findViewById(R.id.account_editor);
        mPasswordEditor = findViewById(R.id.password_editor);
        mLoginSubmitButton = findViewById(R.id.login_submit_button);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPresenter.onPause();
    }

    @Override
    public void render() {
//        if (!LifeApplication.getInstance().getCurrentUser().getUserroleid().equals("2")) {
//            Toast.makeText(this, "暂不支持除学生账号以外的账号登录", Toast.LENGTH_SHORT).show();
//            LifeApplication.getInstance().release();
//            UserSharedPreference preference = UserSharedPreference.getInstance(getContext());
//            preference.clear();
//            mAccountEditor.setText("");
//            mPasswordEditor.setText("");
//        } else {
//            //跳转到主页,并销毁当前界面
//            getNavigator().navigateToMain(getContext());
//            finish();
//        }
        getNavigator().navigateToMain(getContext());
        finish();
    }

    @Override
    public void showProgress() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("正在登录...");
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
        }

        mProgressDialog.show();
    }

    @Override
    public void hideProgress() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }
}
